[LegacyColorValue = true]; 

{ TSM Martingales : Straight Martingales betting method applied to
	a data series
  Copyright 1994-1999, P J Kaufman. All rights reserved. }

{	This method increases the size of the contracts after each
	loss (by "factor"), and starts again at the base "size" 
	after each win. In classic Martingales, factor = 2.0. }

{	length1 = length of moving average 1 (faster or slower)
	size = initial contracts
	factor = increase in number of contracts after loss
	maxcount = maximum number of days in the trade }

	input: period(20), size(2), factor(2.0), leveragecap(5);
	vars:  trend(0), ncontr(0), posentry(0), signal(0);


	if currentbar = 1 then ncontr = size;
	
	trend = average(close, period);

{ buy when faster is above slower }
	if trend > trend[1] and signal <> 1 then begin
		if signal = -1 then begin
			Buy to Cover This Bar  at close;
			signal = 0;
			if posentry - close < 0 then begin
					if ncontr/size < leveragecap then ncontr = ncontr*factor;
					end
				else begin
					ncontr = size;
				end;
			end;
		Buy This Bar intportion(ncontr) contracts at close;
		posentry = close;
		signal = 1;
		end;
	
{ sell when faster is below slower }		
	if trend < trend[1] and signal <> -1 then begin
		if signal = 1 then begin
			Sell This Bar at close;
			signal = 0;
			if close - posentry < 0 then begin
					if ncontr/size < leveragecap then ncontr = ncontr*factor;
					end
				else begin
					ncontr = size;
				end;
			end;
		Sell Short This Bar intportion(ncontr) contracts at close;
		posentry = close;
		signal = -1;
		end;

	if currentbar = 1 then print(file("c:\TSM5\Martingales.csv"),"Date,NetPL,Position");
	
	print(file("c:\TSM5\Martingales.csv"),date:8:0, ",",
				netprofit+openpositionprofit:8:2, ",", signal*ncontr:5:3);